
package com.e885.util.numeric;

import com.e885.constant.util.CarryConstant;
import com.e885.exception.E885UtilException;

/**
 * 
 * @author Grady.Kao
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2000-2008
 */
public class LongUtil
{
	/**
	 * Parse String to be primitive long.<br>
	 * If the instance of the String(source) is null or its length is zero, we will return zero.
	 * 
	 * @param source to be parsed
	 * @param carry carry rule, {@link com.e885.constant.util.CarryConstant}
	 * @return a primitive long
	 * @throws E885UtilException can't pase source to be primitive long
	 */
	public static long parseString2Primitive( String source, int carry ) throws E885UtilException
	{
		return longValue( parseString2Long( source, carry ) );
	}
	
	/**
	 * Parse String to be Long.<br>
	 * If the instance of the String(source) is null or its length is zero, we will return null.
	 * 
	 * @param source to be parsed
	 * @param carry carry rule, reference:{@link com.e885.constant.util.CarryConstant}
	 * @return a Long
	 * @throws E885UtilException can't pase string to be Long
	 */
	public static Long parseString2Long( String source, int carry ) throws E885UtilException
	{
		if( source == null || source.length() == 0 )
			return null;

		if( !( carry == CarryConstant.ROUND_OFF || carry == CarryConstant.UNCONDITIONAL_CARRY || carry == CarryConstant.UNCONDITIONAL_DISCARD ) )
			throw new IllegalArgumentException( "carry is error" );

		try
		{
			if( source.indexOf( "." ) != -1 )
			{
				long intTemp = 0;

				double d = Double.parseDouble( source );

				if( carry == CarryConstant.UNCONDITIONAL_DISCARD )
					intTemp = ( long )d;
				else if( carry == CarryConstant.UNCONDITIONAL_CARRY )
					intTemp = ( long )d + 1;
				else
					intTemp = ( long )( d + 0.5 );

				return new Long( intTemp );
			}

			return new Long( source );
		}
		catch( NumberFormatException e )
		{
			throw new E885UtilException( "Can't parse string to be Long:" + source );
		}
	}

	public static long longValue( Long obj )
	{
		if( obj == null )
			return 0l;

		return obj.longValue();
	}
}
